<template>
  <view class="edit-profile-page">
    <!-- 自定义导航栏 -->
    <view class="profile-content">
      <!-- 头像 -->
      <view class="profile-item" @click="chooseAvatar">
        <text class="item-label">头像</text>
        <view class="item-value">
          <image class="avatar" :src="avatarUrl || defaultAvatar" mode="aspectFill" />
          <uv-icon name="arrow-right" size="16" color="#999"></uv-icon>
        </view>
      </view>

      <!-- 昵称 -->
      <view class="profile-item" @click="openNicknamePopup">
        <text class="item-label">昵称</text>
        <view class="item-value">
          <text class="value-text">{{ nickname || '未设置' }}</text>
          <uv-icon name="arrow-right" size="16" color="#999"></uv-icon>
        </view>
      </view>

      <!-- 性别 -->
      <view class="profile-item" @click="openGenderPicker">
        <text class="item-label">性别</text>
        <view class="item-value">
          <text class="value-text">{{ genderText }}</text>
          <uv-icon name="arrow-right" size="16" color="#999"></uv-icon>
        </view>
      </view>

      <!-- 邮箱 -->
      <view class="profile-item" @click="openEmailPopup">
        <text class="item-label">邮箱</text>
        <view class="item-value">
          <text class="value-text">{{ email || '未设置' }}</text>
          <uv-icon name="arrow-right" size="16" color="#999"></uv-icon>
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="save-btn-wrapper">
      <view 
        class="save-btn" 
        :class="{ disabled: saving }"
        @click="saveProfile"
      >
        <text class="save-btn-text">{{ saving ? '保存中...' : '保存' }}</text>
      </view>
    </view>

    <!-- 昵称编辑弹窗 -->
    <uv-popup
      ref="nicknamePopup"
      mode="center"
      :close-on-click-overlay="true"
      :round="20"
    >
      <view class="nickname-dialog">
        <text class="dialog-title">修改昵称</text>
        <view class="dialog-content">
          <uv-input
            v-model="tempNickname"
            placeholder="请输入昵称"
            maxlength="20"
            border="surround"
            :custom-style="{ padding: '20rpx' }"
          />
          <view class="input-tip">{{ tempNickname.length }}/20</view>
        </view>
        <view class="dialog-buttons">
          <view class="dialog-btn dialog-btn-cancel" @click="closeNicknamePopup">
            <text class="dialog-btn-text">取消</text>
          </view>
          <view class="dialog-btn dialog-btn-confirm" @click="confirmNickname">
            <text class="dialog-btn-text">确定</text>
          </view>
        </view>
      </view>
    </uv-popup>

    <!-- 性别选择器 -->
    <uv-picker
      ref="genderPicker"
      :columns="genderOptions"
      @confirm="onGenderConfirm"
      @cancel="closeGenderPicker"
    ></uv-picker>

    <!-- 邮箱输入弹窗 -->
    <email-input-popup
      ref="emailPopup"
      @confirm="onEmailConfirm"
      @cancel="onEmailCancel"
    ></email-input-popup>
  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { updateUserInfo } from '@/api/user'
import { uploadImage } from '@/api/ai'
import EmailInputPopup from '@/components/email-input-popup/email-input-popup.vue'

export default {
  name: 'EditProfile',
  components: {
    EmailInputPopup
  },
  data() {
    return {
      statusBarHeight: 0,
      nickname: '',
      tempNickname: '', // 临时昵称，用于弹窗编辑
      gender: '',
      email: '', // 邮箱
      avatarUrl: '',
      defaultAvatar: '/static/images/user-v2/avatar-default.png',
      saving: false,
      uploading: false,
      genderOptions: [
        [
          { text: '未知', value: 'UNKNOWN' },
          { text: '男', value: 'MALE' },
          { text: '女', value: 'FEMALE' }
        ]
      ]
    }
  },
  computed: {
    ...mapState('user', ['userMsg']),
    genderText() {
      const genderMap = {
        'MALE': '男',
        'FEMALE': '女',
        'UNKNOWN': '未知'
      }
      return genderMap[this.gender] || '未设置'
    }
  },
  async created() {
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync()
    this.statusBarHeight = systemInfo.statusBarHeight || 0
    
    // 获取最新的用户信息
    await this.refreshUserInfo()
  },
  methods: {
    ...mapActions('user', ['getUserMsg', 'setNickName', 'setAvatar']),

    /**
     * 初始化用户信息
     */
    initUserInfo() {
      this.nickname = this.userMsg.nickname || ''
      this.avatarUrl = this.userMsg.avatarUrl || ''
      this.gender = this.userMsg.gender || 'UNKNOWN'
      this.email = this.userMsg.email || ''
    },

    /**
     * 刷新用户信息
     */
    async refreshUserInfo() {
      try {
        await this.getUserMsg()
        this.initUserInfo()
      } catch (error) {
        console.error('刷新用户信息失败:', error)
      }
    },

    /**
     * 返回上一页
     */
    goBack() {
      uni.navigateBack()
    },

    /**
     * 打开昵称编辑弹窗
     */
    openNicknamePopup() {
      this.tempNickname = this.nickname
      this.$refs.nicknamePopup.open()
    },

    /**
     * 关闭昵称编辑弹窗
     */
    closeNicknamePopup() {
      this.$refs.nicknamePopup.close()
    },

    /**
     * 确认修改昵称
     */
    confirmNickname() {
      const trimmed = this.tempNickname.trim()
      if (!trimmed) {
        uni.showToast({
          title: '昵称不能为空',
          icon: 'none'
        })
        return
      }
      this.nickname = trimmed
      this.closeNicknamePopup()
    },

    /**
     * 打开性别选择器
     */
    openGenderPicker() {
      console.log('打开性别选择器')
      this.$refs.genderPicker.open()
    },

    /**
     * 关闭性别选择器
     */
    closeGenderPicker() {
      this.$refs.genderPicker.close()
    },

    /**
     * 选择头像
     */
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          this.uploadAvatarImage(tempFilePath)
        },
        fail: (err) => {
          console.error('选择图片失败:', err)
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          })
        }
      })
    },

    /**
     * 上传头像图片
     * @param {string} filePath - 本地文件路径
     */
    async uploadAvatarImage(filePath) {
      console.log('开始上传头像，文件路径:', filePath)
      uni.showLoading({
        title: '上传中...',
        mask: true
      })

      try {
        const result = await uploadImage(filePath)
        console.log('上传头像成功:', result)

        // uploadImage 返回的数据结构：{ code: 200, message: '', data: '图片URL', timestamp: 0 }
        this.avatarUrl = result.data

        uni.hideLoading()
        uni.showToast({
          title: '上传成功',
          icon: 'success',
          duration: 1500
        })

      } catch (error) {
        uni.hideLoading()
        console.error('上传头像失败:', error)
        uni.showToast({
          title: error.message || '上传失败',
          icon: 'none'
        })
      }
    },

    /**
     * 性别选择确认 
     * @param {Object} e - 选择事件
     */
    onGenderConfirm(e) {
      console.log('性别选择确认:', e)
      const { value } = e
      if (value && value[0]) {
        this.gender = value[0].value
        console.log('已选择性别:', this.gender)
      }
      this.closeGenderPicker()
    },

    /**
     * 打开邮箱编辑弹窗
     */
    openEmailPopup() {
      this.$refs.emailPopup.open()
    },

    /**
     * 邮箱输入弹窗确认
     */
    onEmailConfirm(email) {
      console.log('确认输入邮箱:', email)
      this.email = email
    },

    /**
     * 邮箱输入弹窗取消
     */
    onEmailCancel() {
      console.log('取消输入邮箱')
    },

    /**
     * 保存用户资料
     * 注意：只更新昵称和性别，不包含头像
     */
    async saveProfile() {
      if (!this.nickname.trim()) {
        uni.showToast({
          title: '请输入昵称',
          icon: 'none'
        })
        return
      }

      // 构建更新数据
      const updateData = {
        nickname: this.nickname.trim(),
        gender: this.gender,
        avatarUrl: this.avatarUrl,
        email: this.email
      }

      console.log('开始保存用户资料，数据:', updateData)
      this.saving = true

      try {
        const response = await updateUserInfo(updateData)
        
        // 更新Vuex中的用户信息
        this.$store.commit('user/SET_USER_MSG', {
          ...this.$store.state.user.userMsg,
          nickname: updateData.nickname,
          gender: updateData.gender,
          avatarUrl: updateData.avatarUrl,
          email: updateData.email
        })
        console.log('Vuex状态已更新')

        // 同步更新旧的 state 字段以保持兼容性
        this.setNickName(updateData.nickname)

        this.saving = false
        
        uni.showToast({
          title: '保存成功',
          icon: 'none',
          duration: 1500
        })

        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)

      } catch (error) {
        this.saving = false
        console.error('保存失败，错误信息:', error)
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.edit-profile-page {
  background-color: #f8f8f8;
  overflow: hidden; /* 防止页面滚动 */
  display: flex;
  flex-direction: column;  
}

/* 自定义导航栏 */
.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  z-index: 1000;
  border-bottom: 1rpx solid #eee;
}

.navbar-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 44px;
  padding: 0 16rpx;
}

.navbar-left,
.navbar-right {
  width: 80rpx;  
  height: 100%;
  display: flex;
  align-items: center;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

/* 内容区域 */
.profile-content {
  flex: 1;
  padding: 24rpx 0;
  background-color: #fff;
  overflow-y: auto; /* 内容区域可滚动 */
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
}

.profile-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 32rpx;
  border-bottom: 1rpx solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }
}

.item-label {
  font-size: 32rpx;
  color: #333;
}

.item-value {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #f5f5f5;
}

.value-text {
  font-size: 28rpx;
  color: #666;
  margin-right: 8rpx;
}

/* 保存按钮 */
.save-btn-wrapper {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 24rpx 32rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  background-color: #fff;
  border-top: 1rpx solid #eee;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05); /* 添加阴影增强层次感 */
  z-index: 100;
}

.save-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #00d4aa, #00c299);
  border-radius: 44rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 212, 170, 0.35);
  transition: all 0.3s ease;

  &:active:not(.disabled) {
    transform: scale(0.98);
    box-shadow: 0 4rpx 16rpx rgba(0, 212, 170, 0.35);
  }

  &.disabled {
    background: #e0e5eb;
    box-shadow: none;
    
    .save-btn-text {
      color: #999;
    }
  }
}

.save-btn-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #fff;
  letter-spacing: 2rpx;
}

/* 昵称弹窗样式 */
.nickname-dialog {
  width: 600rpx;
  padding: 48rpx 40rpx 40rpx;
  background: #fff;
  border-radius: 20rpx;
}

.dialog-title {
  display: block;
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  text-align: center;
  margin-bottom: 40rpx;
}

.dialog-content {
  margin-bottom: 40rpx;
  position: relative;
}

.input-tip {
  position: absolute;
  right: 24rpx;
  bottom: -32rpx;
  font-size: 24rpx;
  color: #969799;
}

.dialog-buttons {
  display: flex;
  gap: 20rpx;
}

.dialog-btn {
  flex: 1;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12rpx;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
  }
}

.dialog-btn-cancel {
  background: #f5f5f5;
  
  .dialog-btn-text {
    color: #666;
  }
}

.dialog-btn-confirm {
  background: linear-gradient(135deg, #00d4aa, #00c299);
  box-shadow: 0 4rpx 12rpx rgba(0, 212, 170, 0.25);
  
  .dialog-btn-text {
    color: #fff;
  }
}

.dialog-btn-text {
  font-size: 28rpx;
  font-weight: 500;
}
</style>

